// 物理引擎模块
// 使用全局Matter对象，因为Matter.js是通过script标签加载的
const { World, Bodies, Body, Engine, Runner, Events } = Matter;

// 物理引擎相关变量
let engine, runner;

// 初始化物理引擎
function initPhysics() {
    if (runner) Runner.stop(runner);
    if (engine) Engine.clear(engine);
    
    // 创建物理引擎
    engine = Engine.create();
    engine.gravity.y = 1.2;

    // 创建运行器
    runner = Runner.create();
    Runner.run(runner, engine);
    
    return { engine, runner };
}

// 停止物理引擎
function stopPhysics() {
    if (runner) Runner.stop(runner);
    if (engine) World.clear(engine.world);
}

// 创建马里奥物体
function createMario(x, y) {
    const mario = Bodies.rectangle(x, y, 30, 40, {
        restitution: 0.1,
        friction: 0.05,
        density: 0.001,
        label: 'mario'
    });
    
    // 确保初始速度为零
    Body.setVelocity(mario, { x: 0, y: 0 });
    Body.setAngle(mario, 0);
    
    return mario;
}

// 创建平台
function createPlatform(x, y, width, height, label = 'platform') {
    return Bodies.rectangle(x, y, width, height, {
        isStatic: true,
        label: label
    });
}

// 创建敌人
function createEnemy(x, y) {
    return Bodies.rectangle(x, y, 30, 30, {
        restitution: 0.2,
        friction: 0.05,
        label: 'enemy'
    });
}

// 创建金币
function createCoin(x, y) {
    return Bodies.circle(x, y, 10, {
        isStatic: true,
        isSensor: true,
        label: 'coin'
    });
}

export { 
    initPhysics, 
    stopPhysics, 
    createMario, 
    createPlatform, 
    createEnemy, 
    createCoin,
    World,
    Body,
    Engine,
    Runner
};